<?php
	require_once($_SERVER["DOCUMENT_ROOT"]."/alerter/modules/alert.php");
	require_once($_SERVER["DOCUMENT_ROOT"]."/alerter/modules/base_mod.php");

	class AlertMod extends AlertBaseMod {
            
		private function getFactions(){
                    $fed = v($_REQUEST, "showfed");
                    $emp = v($_REQUEST, "showemp");
                    $uni = v($_REQUEST, "showuni");
                    $neu = v($_REQUEST, "showneu");
                    $inString = "1,2,3,4";
                    if($fed == "false")
                        $inString = str_replace("1,", "", $inString);
                    if($emp == "false")
                        $inString = str_replace("2,", "", $inString);
                    if($uni == "false")
                        $inString = str_replace("3,", "", $inString);
                    if($neu == "false")
                        $inString = trim(str_replace("4", "", $inString), ",");
                    if(strlen($inString) > 0)
                        return $inString;
                    else
                        return "1";
                }
                
                public function getMsgThreats(){
                    $threats =  "<div id='po_mfa_info_text'><b>";
                    
                    $factions = self::getFactions();
                    
                    if(strlen($factions) > 0){
                        $conn = self::getConnection();
                        $sql = "SELECT a.cluster, COUNT(*) AS Qty FROM alerts a INNER JOIN cluster c ON c.abbreviation = a.cluster WHERE c.faction IN (" . $factions . ") AND a.cluster <> '' AND a.cleared = 0 AND a.superceded = 0 GROUP BY cluster";
                        $rows = mysql_query($sql, $conn);
                        if(rows){
                            while ($row = mysql_fetch_assoc($rows)){
                                $threats .= "<span class='nobreak'>";
                                $threats .= "<a target='_blank' title='Alerts in " . $row["cluster"] . "' href='" . AlertSettingsMod::LOGGER_BASE_URL . "alerts.php?cluster=" . mb_strtolower($row["cluster"]) . "'>";
                                $threats .= "<font style='color:red;'>" . $row["cluster"] . ":&nbsp;</font>" . $row["Qty"] . "&nbsp;";
                                $threats .= "</a>";
                                $threats .= "</span>";
                            }
                        }
                    }

                    return $threats . "</b></div>";
                }
                
                public function getSDOThreats(){
			$threats = "<div id='orion'>";
			$conn = self::getConnection();
			$sql = "SELECT a.id, a.pid, a.when, a.alert_type, a.cluster, a.sector, a.coords, a.attacker, a.outcome, a.defender, a.additional, a.detail, (SELECT COUNT(*) FROM alerts c WHERE c.sector = a.sector and c.cleared = 0 and c.superceded = 0) AS sector_count FROM alerts a WHERE a.cleared = 0 AND a.superceded = 0 AND a.cluster <> '' ORDER BY a.cluster, a.sector";
                        $rows = mysql_query($sql, $conn);
                        if(rows){
                            $sectorThreatCount = 0;
                            $currentThreat = 0;
                            $alertTypeText = "";
                            while ($row = mysql_fetch_assoc($rows)){
                                $logLink = "";
                                $logLinkEnd = "";
                                if($sectorThreatCount == 0){
                                    $sectorThreatCount = $row["sector_count"];
                                    $currentThreat = 0;
                                    $threats .= "<div alerts='" . $sectorThreatCount . "' sector='" . $row["sector"] . "' cluster='" . $row["cluster"] . "'>";
                                }
                                if($currentThreat < $sectorThreatCount){
                                    $currentThreat++;
                                    $coords = explode(",", trim($row["coords"], "[]"));
                                    $xCoord = trim($coords[0]);
                                    $yCoord = trim($coords[1]);
                                    $alertType = $row["alert_type"];
                                    switch ($alertType){
                                        case "CMBT":
                                            if(stristr($row["additional"], "Ambushed") != false){
                                                $alertTypeText = "Ambush";
                                            }else{
                                                $alertTypeText = "Combat";
                                            }
                                            $logLink = "<a href='javascript:SDOshowCombat(".(string)$row["pid"].")'>";
                                            $logLinkEnd = "</a>";
                                            break;
                                        case "HACK":
                                            $alertTypeText = "Hack";
                                            $logLink = "<a href='javascript:SDOshowHack(".(string)$row["pid"].")'>";
                                            $logLinkEnd = "</a>";
                                            break;
                                        case "SGHT":
                                            $alertTypeText = "Sighting";
                                            break;
                                        case "MANL":
                                            $alertTypeText = "Manual alert";
                                            break;
                                        case "SAFE":
                                            $alertTypeText = "Safe tile";
                                            break;
                                    }
                                    //TODO: create a nice text for type ("Ambushed", "PvP", "Sighted" etc)
                                    $threats .= "<div xcoord='" . $xCoord . "' ycoord='" . $yCoord . "' pilot='" . $row["attacker"] . "' type='" . $row["alert_type"] . "' alertid='" . $row["id"] . "' title='" . $alertTypeText . ": " . $row["attacker"] . " " . trim($row["outcome"]) . " " . trim($row["defender"]) . " -- Reported: " . $row["when"] . "'>" . $logLink . $row["coords"] . " " . $alertTypeText . $logLinkEnd . "</div>";
                                }
                                if($currentThreat == $sectorThreatCount){
                                    $sectorThreatCount = 0;
                                    $threats .= "</div>";
                                }
                            }
                            $threats .= "</div>";
                        }
                        return $threats . "</div>";
                }
            
		public function getThreats(){
			$threats = "";
			$conn = self::getConnection();
			$sql = "SELECT * FROM alerts a WHERE a.cleared = 0 AND a.superceded = 0 ORDER BY a.sector";
			$rows = mysql_query($sql, $conn);
			$currentSector = "";
			$alertCount = 0;
			$sectorThreatCount = 0;
			while ($row = mysql_fetch_assoc($rows)) {
				$sector = $row["sector"];
				$coords = trim($row["coords"], "[]");
				if ($sector != $currentSector){
					$currentSector = $sector;
					if ($alertCount > 0) {
						$threats = rtrim($threats, ";");
						$threats = $threats.";".$sectorThreatCount."|".$currentSector.";".$row["attacker"].":".$coords.";";
					}else{
						$threats = $currentSector.";".$row["attacker"].":".$coords.";";
					}
					$sectorThreatCount = 1;
				}else{
					$threats = $threats.$row["attacker"].":".$coords.";";
					$sectorThreatCount++;
				}
				$alertCount++;
			}
			return $threats.$sectorThreatCount;
		}
		
		public function clearTile($remtile){
			if ($remtile != ""){
				$data = explode(";", $remtile);
				$sector = $data[0];
				$soords = "[".$data[1]."]";
				$conn = self::getConnection();
				$sql = sprintf(
					"update alerts set cleared = 1 where sector = '%s' and coords = '%s'", 
					mysql_real_escape_string($sector),
					mysql_real_escape_string($soords)
					);
				//echo $sql;
				mysql_query($sql, $conn);
			}
		}
	
		public function getAlerts(){
			$alerts = self::getAllAlerts();
			$response = "";
			foreach($alerts as $alt):
				$response = $response .$alt->getCluster()."|".$alt->getSector()."|".$alt->getCoords()."|".$alt->getReason()."|".$alt->getOffender()."|".$alt->getName().";";
			endforeach;
			return $response;
		}
		
		private function getAllAlerts() {
			$alerts = array();
			$conn = self::getConnection();
			$sql = "SELECT * FROM alerts a where a.cleared = 0 and a.superceded = 0 ORDER BY a.when desc";
			//echo $sql;
			$rows = mysql_query($sql, $conn); 
			while ($row = mysql_fetch_assoc($rows)) {
				$clustr = $row["cluster"];
				$rsn = $row["additional"];
				if ($rsn != "Ambushed") $rsn = "PvP";
				if ($row["type"] == "Building attack") $rsn = "Building attack";
				if (is_null($clustr)) $clustr = "";
				$alert =
					new Alert(
						$row["when"],
						$clustr,
						$row["sector"],
						$row["coords"],
						$row["type"],
						$row["attacker"],
						$row["defender"],
						$row["alert_type"],
						$row["id"],
						$row["cleared"]
					);
			//echo $alert->getSector();
			$alerts[] = $alert;
			}
			//echo count("     ".$alerts);
			return $alerts;
			
		}
		
		public function getAlertsForList($cluster) {
			$alerts = array();
			$conn = self::getConnection();
			if (!empty($cluster))
				$sql = "SELECT * FROM alerts a where a.cluster = '".$cluster."' ORDER BY a.when desc";
			else
				$sql = "SELECT * FROM alerts a ORDER BY a.when desc";
			//echo $sql;
			$rows = mysql_query($sql, $conn); 
			while ($row = mysql_fetch_assoc($rows)) {
				$clustr = $row["cluster"];
				$rsn = $row["additional"];
				if ($rsn != "Ambushed") $rsn = "PvP";
				if ($row["type"] == "Building attack") $rsn = "Building attack";
				if (is_null($clustr)) $clustr = "";
				$alert =
					new Alert(
						$row["when"],
						$clustr,
						$row["sector"],
						$row["coords"],
						$row["type"],
						$row["attacker"],
						$row["defender"],
						$row["alert_type"],
						$row["pid"],
						$row["cleared"],
                                                $row["superceded"]
					);
			//echo $alert->getSector();
			$alerts[] = $alert;
			}
			//echo count("     ".$alerts);
			return $alerts;
			
		}
		
		public function getManualAlertById($id) {
			$conn = self::getConnection();
			$sql = sprintf(
				"select * from manual_alert where id = %d",
				$id
				);
			$rows = mysql_query($sql, $conn);
			$row = mysql_fetch_assoc($rows);
			return new ManualAlert(
					$row["alerter_id"],
					$row["type"],
					$row["sector"],
					$row["coords"],
					$row["header"],
					$row["detail"],
					$row["date"]
				); 
		}
                
		public function getSafeTileById($id) {
			$conn = self::getConnection();
			$sql = sprintf(
				"select * from safe_tile where id = %d",
				$id
				);
			$rows = mysql_query($sql, $conn);
			$row = mysql_fetch_assoc($rows);
			return new SafeTile(
					$row["reporter_id"],
					$row["sector"],
					$row["coords"],
					$row["comment"],
					$row["date"]
				); 
		}
                
		public function getSightingById($id) {
			$conn = self::getConnection();
			$sql = sprintf(
				"select * from sighting where id = %d",
				$id
				);
			$rows = mysql_query($sql, $conn);
			$row = mysql_fetch_assoc($rows);
			return new SightingAlert(
					$row["sighter_id"],
					$row["sector"],
					$row["coords"],
					$row["pilot_name"]
				); 
		}
		
		public function addSighting($sighting) {
			$conn = self::getConnection();
			$sql = sprintf(
				"insert into sighting (sighter_id, date, sector, coords, pilot_name) values (%d, utc_timestamp(), '%s', '%s', '%s');",
				$sighting->getSighterID(),
				$sighting->getSector(),
				$sighting->getCoords(),
				$sighting->getPilotName()
				);
			//echo $sql;	
			mysql_query($sql, $conn);
		}
		
		public function addManualAlert($manualAlert) {
			$conn = self::getConnection();
			$sql = sprintf(
				"insert into manual_alert (type, alerter_id, sector, coords, date, header, detail) values (%d, %d, '%s', '%s', utc_timestamp(), '%s', '%s')", 
				$manualAlert->getAlertType(),
				$manualAlert->getAlerterId(), 
				mysql_real_escape_string($manualAlert->getSector()),
				mysql_real_escape_string($manualAlert->getCoords()),
				mysql_real_escape_string($manualAlert->getHeader()),
				mysql_real_escape_string($manualAlert->getDetail())
				);
			//echo $sql;	
			mysql_query($sql, $conn);
		}
                
                public function addSafeTile($safeTile) {
                    $conn = self::getConnection();
                    $sql = sprintf(
                            "insert into safe_tile (reporter_id, sector, coords, date, comment) values (%d, '%s', '%s', utc_timestamp(), '%s')",
                            $safeTile->getAlerterId(),
                            mysql_real_escape_string($safeTile->getSector()),
                            mysql_real_escape_string($safeTile->getCoords()),
                            mysql_real_escape_string($safeTile->getComment())
                            );
                    mysql_query($sql, $conn);
                }
		
		public function getManualAlertTypeById($id) {
			$conn = self::getConnection();
			$sql = "select alert_type from manual_alert_type where id = ".$id;
			$rows = mysql_query($sql, $conn);
			$row = mysql_fetch_assoc($rows);
			if (!row)
				return null;
			else
				return $row["alert_type"];
		}
		
		public function getManualAlertTypes() {
			$alertTypes = array();
			$conn = self::getConnection();
			$sql = "SELECT * FROM manual_alert_type";
			$rows = mysql_query($sql, $conn);
			while ($row = mysql_fetch_assoc($rows)) {
				$alertType =
					new ManualAlertType(
						$row["id"],
						$row["alert_type"]
					);
				$alertTypes[] = $alertType;
			}
			return $alertTypes;
		}
		
		public function getSectors() {
			$sectors = array();
			$conn = self::getConnection();
			$sql = "SELECT * FROM sector order by sector";
			$rows = mysql_query($sql, $conn);
			while ($row = mysql_fetch_assoc($rows)) {
				$sectors[] = $row["sector"];
			}
			return $sectors;
		}

	}
?>